package ioc

import "fmt"

// IOC 注册 获取 Init
type IocContainer interface {
	Registry(string, Object)
	Get(string) Object
	Init() error
}

var _ IocContainer = (*MapIocContainer)(nil)

// Map类型IOC
type MapIocContainer struct {
	name    string
	storage map[string]Object
}

type Object interface {
	Init() error
}

func (m *MapIocContainer) Registry(name string, object Object) {
	m.storage[name] = object
}

func (m *MapIocContainer) Get(name string) Object {
	return m.storage[name]
}

func (m *MapIocContainer) Init() error {
	if len(m.storage) == 0 {
		return fmt.Errorf("%s %s IOC 为空", m.name, m.storage)
	}
	for n, o := range m.storage {
		fmt.Printf("%s %s %v 开始初始化...\n", m.name, n, o)

		if err := o.Init(); err != nil {
			fmt.Printf("%s %s %v 初始化失败\n", m.name, n, o)
			return err
		}
		fmt.Printf("%s %s %v 初始化成功\n", m.name, n, o)

	}
	return nil
}

var Controller IocContainer = &MapIocContainer{
	name:    "controller",
	storage: make(map[string]Object),
}

var Api IocContainer = &MapIocContainer{
	name:    "api",
	storage: make(map[string]Object),
}
